// src/pages/LockScreen/index.tsx
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import styles from './index.module.css';

interface FormValues {
    password: string;
}

const LockScreen: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm<FormValues>();
    const navigate = useNavigate();
    const location = useLocation();
    const isInitialized = useRef(false);

    // 验证规则
    const validationRules = [
        {
            required: true,
            message: '请填写密码',
        },
        {
            min: 6,
            max: 18,
            message: '密码格式错误（6-18位）',
        },
        {
            validator: async (_: any, value: string) => {
                if (!value || value.length < 6) {
                    return Promise.resolve();
                }
                const trimmedVal = value.trim();
                const voucher = sessionStorage.getItem('voucher');
                if (!voucher || voucher !== 'Login-credentials') {
                    throw new Error('未检测到登录状态，请重新登录');
                }
                const storedPwd = sessionStorage.getItem('loginPassword');
                if (!storedPwd) {
                    throw new Error('未找到密码信息，请重新登录');
                }
                if (trimmedVal !== storedPwd) {
                    throw new Error('密码错误请重新输入');
                }
                return Promise.resolve();
            }
        }
    ];

    const handleUnlock = async () => {
        try {
            setLoading(true);
            await form.validateFields();
            
            // 关键修复：设置解锁标记
            sessionStorage.setItem('isUnlocking', 'true');
            
            // 清除锁屏状态
            localStorage.removeItem('isLocked');
            const redirectPath = localStorage.getItem('attemptedPath') || '/welcome';
            
            // 确保路径有效
            const safeRedirectPath = redirectPath === '/lock' ? '/welcome' : redirectPath;
            localStorage.removeItem('attemptedPath');

            console.log('解锁跳转:', safeRedirectPath);
            
            // 显示成功消息
            message.success('解锁成功', 1);
            
            // 关键修复：使用setTimeout确保状态更新完成后再跳转
            setTimeout(() => {
                // 使用window.location.href强制刷新页面，确保状态同步
                window.location.href = safeRedirectPath;
            }, 500);

        } catch (error) {
            console.log('解锁失败:', error);
            sessionStorage.removeItem('isUnlocking');
            setLoading(false);
        }
    };

    // 简化输入框事件处理
    const handleInputFocus = () => {
        form.setFields([{ name: 'password', errors: [] }]);
    };

    const handleInputChange = () => {
        // 简化实时验证逻辑
    };

    const handleInputBlur = () => {
        const value = form.getFieldValue('password');
        if (value && value.trim() !== '') {
            form.validateFields(['password']);
        }
    };

    // 页面加载时设置
    useEffect(() => {
        const timer = setTimeout(() => {
            const input = document.querySelector(`.${styles['password-item']} input`) as HTMLInputElement;
            if (input) {
                input.focus();
            }
            isInitialized.current = true;
        }, 100);

        // 设置锁屏状态
        localStorage.setItem('isLocked', 'true');
        
        // 清除可能存在的旧标记
        sessionStorage.removeItem('isUnlocking');

        return () => {
            clearTimeout(timer);
        };
    }, []);

    return (
        <div className={styles['lock-screen-container']}>
            <div className={styles['lock-modal']}>
                <div className={styles['title-group']}>
                    <div className={styles['lock-status']}>当前是锁屏状态</div>
                    <div className={styles['welcome-text']}>欢迎回来</div>
                </div>

                <Form
                    form={form}
                    layout="vertical"
                    className={styles['lock-form']}
                    initialValues={{ password: '' }}
                >
                    <Form.Item
                        name="password"
                        rules={validationRules}
                        className={styles['password-item']}
                        validateFirst
                    >
                        <Input.Password
                            placeholder="请输入密码"
                            size="large"
                            prefix={<LockOutlined className={styles['lock-icon']} />}
                            onFocus={handleInputFocus}
                            onChange={handleInputChange}
                            onBlur={handleInputBlur}
                            onPressEnter={handleUnlock}
                            style={{
                                height: '42px',
                                borderRadius: '6px',
                                fontSize: '14px'
                            }}
                            autoComplete="new-password"
                        />
                    </Form.Item>

                    <Form.Item className={styles['submit-item']}>
                        <Button
                            type="primary"
                            className={styles['unlock-btn']}
                            onClick={handleUnlock}
                            loading={loading}
                            block
                            style={{
                                height: '42px',
                                fontSize: '16px',
                                fontWeight: 500
                            }}
                        >
                            {loading ? '解锁中...' : '解锁进入系统'}
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default LockScreen;